package com.compass.doctor.ui.mine

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.databinding.ActivityMyEvaluateBinding
import com.compass.doctor.ui.mine.adapter.EvaluateAdapter
import com.compass.doctor.ui.mine.adapter.EvaluateTagAdapter
import com.compass.doctor.ui.mine.viewmodel.MineViewModel
import com.compass.framework.ext.gone
import com.compass.framework.ext.load
import com.compass.framework.ext.visible
import com.compass.framework.model.PrescriptionStatus
import com.compass.framework.utils.StatusBarSettingHelper
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import kotlin.math.abs

/**
 * Description： 我的评价
 * Date:2023/12/30 11:09
 */
class EvaluateActivity : BaseVBActivity<ActivityMyEvaluateBinding>(), OnRefreshListener,
    OnLoadMoreListener {
    private lateinit var evaluateTagAdapter: EvaluateTagAdapter
    private var tags: MutableList<PrescriptionStatus> = mutableListOf()
    private var satisfactionDegree: ArrayList<String> = ArrayList()
    private var isSetSG: Boolean = true//是否设置为了 staggeredGridLayoutManager
    private var isSetLin: Boolean = false//是否设置为了 linearLayoutManager
    private var fingerIsUp: Boolean = false //手指是否抬起
    private var isFullFold: Boolean = false//是否完全折叠
    private lateinit var layoutFelManager: FlexboxLayoutManager
    private lateinit var linearLayoutManager: LinearLayoutManager
    private lateinit var evaluateAdapter: EvaluateAdapter

    private var mPage = 1
    private val mineViewModel: MineViewModel by viewModels()

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, EvaluateActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarSettingHelper.setStatusBarTranslucent(this)
        StatusBarSettingHelper.statusBarLightMode(this@EvaluateActivity, true)
        linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)

        layoutFelManager = FlexboxLayoutManager(this)
        layoutFelManager.flexWrap = FlexWrap.WRAP // 按正常方向换行
        layoutFelManager.flexDirection = FlexDirection.ROW // 水平方向
        layoutFelManager.justifyContent = JustifyContent.FLEX_START // 左对齐

//        staggeredGridLayoutManager = StaggeredGridLayoutManager(2, RecyclerView.VISIBLE)
        evaluateTagAdapter = EvaluateTagAdapter()
        initTagView()
        initEvaluateView()

        mBinding.appBarLayout.addOnOffsetChangedListener { appBarLayout, verticalOffset ->

            isFullFold = abs(verticalOffset) >= appBarLayout.totalScrollRange
            changeLayoutManager(!isFullFold)

        }

    }

    private fun initEvaluateView() {
        evaluateAdapter = EvaluateAdapter()
        mBinding.rcyEvaluate.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = evaluateAdapter
        }
        mBinding.refreshLayout.apply {
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener(this@EvaluateActivity)
            setOnLoadMoreListener(this@EvaluateActivity)
        }
    }


    private fun initTagView() {
        mBinding.rcyTab.apply {
            layoutManager = layoutFelManager
            adapter = evaluateTagAdapter
        }
        evaluateTagAdapter.onItemClickListener = { _, position ->
            tags[position].isSelect = !tags[position].isSelect
            evaluateTagAdapter.notifyDataSetChanged()

            satisfactionDegree.clear()
            for (item in tags){
                if (item.isSelect){
                    satisfactionDegree.add(item.value)
                }
            }
            showLoading()
            getEvaluationList()
        }
    }

    /**
     * 修改rcyTag： LayoutManager
     */
    private fun changeLayoutManager(isFullFold: Boolean) {
        if (fingerIsUp) //手指抬起才允许更换布局效果
            if (isFullFold) {
                if (!isSetSG) {
                    isSetSG = true
                    isSetLin = false
                    mBinding.rcyTab.layoutManager = layoutFelManager
                }
            } else {
                if (!isSetLin) {
                    isSetLin = true
                    isSetSG = false
                    mBinding.rcyTab.layoutManager = linearLayoutManager
                }
            }
    }


    override fun initData() {
        mineViewModel.getEvaluationClassification()
        mineViewModel.classLiveData.observe(this) {
            it?.let { evaluation ->
                mBinding.tvFavorableRate.text = "${evaluation.favorableRate}"
                mBinding.tvService.text = "服务人数${evaluation.serviceCount}"
                mBinding.tvEvaluatorsNumber.text = "共${evaluation.commentCount}人评价"
                tags = evaluation.serviceCommentList
                evaluateTagAdapter.setData(tags)
            }


        }
        mineViewModel.evaluateLiveData.observe(this){
            dismissLoading()
            if (mPage == 1) {
                evaluateAdapter.setData(it)
                mBinding.refreshLayout.finishRefresh()
                mBinding.refreshLayout.setEnableLoadMore(load(it?.size))
                if (it.isNullOrEmpty()) {
                    mBinding.emptyView.visible()
                } else {
                    mBinding.emptyView.gone()
                }
            } else {
                mBinding.refreshLayout.finishLoadMore()
                if (!it.isNullOrEmpty()) {
                    evaluateAdapter.addAll(it)
                } else {
                    mBinding.refreshLayout.setEnableLoadMore(false)
                }
            }


        }
        getEvaluationList()
    }


    private fun getEvaluationList() {

        mineViewModel.getEvaluationList(1, satisfactionDegree)
    }


    /**
     * 监听手指是否抬起
     */
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_UP) {
            //记录手指抬起
            fingerIsUp = true
            changeLayoutManager(!isFullFold)
        }
        if (ev?.action == MotionEvent.ACTION_DOWN) {
            //记录手指按下
            fingerIsUp = false
        }
        return super.dispatchTouchEvent(ev);
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mPage = 1
        getEvaluationList()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mPage++
        getEvaluationList()
    }


}